<?php

namespace app\api\controller;

use think\Controller;
use think\facade\Request;
use HTTP_Request2;
use think\Db;
use think\exception\HttpException;

class Common extends Controller
{
    protected $request;

    public function initialize()
    {
        header('Access-Control-Allow-Origin:*');
        $this->page = input('?page') ? input('page') : 1;
        $this->limit = input('?limit') ? input('limit') : 10;
        $this->app = $this->getappinfo(input('appid'));
    }

    public function getappinfo($appid)
    {
        if (!isset($appid) || empty($appid)) {
            return $this->returnjson(400, "appid不存在");
        }
        $appinfo = db("app")->where("appid", $appid)->find();
        if ($appinfo) {
            if ($appinfo["is_state"] == 1) {
                return $this->returnjson(400, "此app已关闭操作");
            }
            return $appinfo;
        } else {
            return $this->returnjson(400, "app不存在");
        }
    }

    /**
     * 解密字符串
     *
     * @param [type] $input
     * @param [type] $securityKey
     */
    public static function WeDecrypt($input, $securityKey)
    {
        $input = urldecode($input);
        $input = openssl_decrypt($input, 'AES-128-ECB', $securityKey);
        if (!$input) {
            return self::returnjson(400, "服务器错误");
        }
        return $input;
    }

    /**
     * 加密字符串
     *
     * @param [type] $input
     * @param [type] $securityKey
     */
    public static function WeDoctorEncrypt($input, $securityKey)
    {
        $inputArr = json_decode($input, true); //转为数组
        if (!is_array($inputArr) || empty($inputArr)) {
            return self::returnjson(400, "服务器错误");
        }
        $input = json_encode($inputArr, JSON_UNESCAPED_UNICODE); //转为json字符串
        //进行Aes加密
        $data = openssl_encrypt($input, 'AES-128-ECB', $securityKey);
        return urlencode($data);
    }

    function returnjson($code = 200, $msg = "success", $data = [])
    {
        $result = [
            "code" => $code,
            "msg" => $msg,
            "data" => $data
        ];
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        die();
    }

    public function successjson($msg = "success", $data = [], $code = 200)
    {
        $result = [
            "code" => $code,
            "msg" => $msg,
            "data" => $data
        ];
        $result = json_encode($result, JSON_UNESCAPED_UNICODE);
        if ($this->app["is_sign"] == 0) {
            $result = $this->WeDoctorEncrypt($result, $this->app["signkey"]);
        }
        return $result;
    }

    public function errorjson($msg = "error", $data = [], $code = 400)
    {
        return $this->successjson($msg, $data, $code);
    }

    public function getaddress($ip = '')
    {
        $request = new HTTP_Request2();
        $request->setUrl('https://ip.useragentinfo.com/json?ip=' . $ip);
        $request->setMethod(HTTP_Request2::METHOD_GET);
        $request->setConfig(array(
            'follow_redirects' => TRUE
        ));
        try {
            $response = $request->send();
            if ($response->getStatus() == 200) {
                return $response->getBody();
            } else {
                return 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
                    $response->getReasonPhrase();
            }
        } catch (HttpException $e) {
            return 'Error: ' . $e->getMessage();
        }
    }

    //递归删除 评论 (删除父级评论下面的所有评论)  无限极递归
    public function getParentdel($commentinfo)
    {
        //不用db助手函数  db助手函数每次都会创建一个链接   会导致达到最大连接数量
        foreach ($commentinfo as $key => $value) {
            $id = $value["id"];
            Db::name("comments")->where("id", $value["id"])->delete();
            $rs = Db::name("comments")->where("parentid", $id)->select();
            $this->getParentdel($rs);
        }
    }

    /**
     * 增加通知消息 (评论 点赞)
     *
     * @param [type] $sender_id   发送者id
     * @param [type] $type  1点赞消息2评论消息
     * @param [type] $postid  帖子id
     * @param [type] $comments_id  评论id
     * @return void
     */
    public function addmessage($sender_id, $type, $postid, $comments_id = '')
    {
        $postinfo = db("article")->where("id", $postid)->find();
        $userinfo = db("user")->where("id", $sender_id)->find();
        if ($postinfo["userid"] == $sender_id) {
            return true;
        }
        if ($type == 1) {
            $title = "点赞消息";
            $content = "您的文章【" . $postinfo["title"] . "】收到了用户【" . $userinfo["nickname"] . "】的点赞";
            $addmessagedata = [
                "title" => $title,
                "content" => $content,
                "sender_id" => $sender_id,
                "appid" => $this->app["appid"],
                "time" => date("Y-m-d H:i:s", time()),
                "postid" => $postid,
                "type" => 1
            ];
            $msgid = db("message")->insertGetId($addmessagedata);
            //增加通知
            $addmsg_userdata = [
                "msg_id" => $msgid,
                "user_id" => $postinfo["userid"]
            ];
            db("message_user")->insert($addmsg_userdata);
        } else {
            $commentsinfo = db("comments")->where("id", $comments_id)->find();
            if ($commentsinfo["parentid"] == 0) {
                $title = "评论消息";
                $content = "您的文章【" . $postinfo["title"] . "】收到了用户【" . $userinfo["nickname"] . "】的评论;内容为：" . $commentsinfo["content"];
                $addmessagedata = [
                    "title" => $title,
                    "content" => $content,
                    "sender_id" => $sender_id,
                    "appid" => $this->app["appid"],
                    "time" => date("Y-m-d H:i:s", time()),
                    "postid" => $postid,
                    "type" => 2
                ];
                $msgid = db("message")->insertGetId($addmessagedata);
                //增加通知
                $addmsg_userdata = [
                    "msg_id" => $msgid,
                    "user_id" => $postinfo["userid"]
                ];
                db("message_user")->insert($addmsg_userdata);
            } else {
                $twocommentsinfo = db("comments")->where("id", $commentsinfo["parentid"])->find();
                $title = "评论回复消息";
                $content = "您的评论【" . $twocommentsinfo["content"] . "】收到了用户【" . $userinfo["nickname"] . "】的回复;内容为：" . $commentsinfo["content"];
                $addmessagedata = [
                    "title" => $title,
                    "content" => $content,
                    "sender_id" => $sender_id,
                    "appid" => $this->app["appid"],
                    "time" => date("Y-m-d H:i:s", time()),
                    "postid" => $postid,
                    "type" => 2
                ];
                $msgid = db("message")->insertGetId($addmessagedata);
                //增加通知
                $addmsg_userdata = [
                    "msg_id" => $msgid,
                    "user_id" => $postinfo["userid"]
                ];
                db("message_user")->insert($addmsg_userdata);
            }
        }
    }

    /**
     * 增加系统消息
     * @param [type] $userid   用户id
     * @param [type] $type  3签到的成功消息4购买成功消息5使用卡密的消息
     * @param [type] $shopid  帖子id 或 卡密id
     */
    public function addSysMessage($type,$userid,$shopid = "")
    {
        //签到的成功消息
        if ($type == 3) {
            if ($this->app["sign_money"] == 0) {
                $money = "";
            } else {
                $money = "金币 = " . $this->app["sign_money"] . ",";
            }
            if ($this->app["sign_exp"] == 0) {
                $exp = "";
            } else {
                $exp = "经验 = " . $this->app["sign_exp"] . ",";
            }
            if ($this->app["sign_vip"] == 0) {
                $vip = "";
            } else {
                $vip = "会员 = " . $this->app["sign_vip"] . "天";
            }
            if($money == "" && $exp == "" && $vip == ""){
                $content = "您于".date("Y-m-d H:i:s", time())."签到成功。";
            }else{
                $content = "您于".date("Y-m-d H:i:s", time())."签到成功，获得".$money.$exp.$vip;
            }
            //签到消息
            $addmessagedata = [
                "title" => "签到成功",
                "content" => $content,
                "sender_id" => 0,
                "appid" => $this->app["appid"],
                "time" => date("Y-m-d H:i:s", time()),
                "type" => 3
            ];
            $msgid = db("message")->insertGetId($addmessagedata);
            //增加通知
            $addmsg_userdata = [
                "msg_id" => $msgid,
                "user_id" => $userid
            ];
            db("message_user")->insert($addmsg_userdata);
        }
        //购买成功消息
        if($type == 4){
            $shopinfo = db("shop")->where("id",$shopid)->find();
            if($shopinfo["type"] == 1){
                $content = "您于".date("Y-m-d H:i:s", time())."购买的商品【".$shopinfo["name"]."】已购买成功，获得".$shopinfo["content"];
            }else{
                $content = "您于".date("Y-m-d H:i:s", time())."购买的商品【".$shopinfo["name"]."】已购买成功，获得会员".$shopinfo["content"]."天";
            }
            $addmessagedata = [
                "title" => "购买成功",
                "content" => $content,
                "sender_id" => 0,
                "appid" => $this->app["appid"],
                "time" => date("Y-m-d H:i:s", time()),
                "type" => 4
            ];
            $msgid = db("message")->insertGetId($addmessagedata);
            //增加通知
            $addmsg_userdata = [
                "msg_id" => $msgid,
                "user_id" => $userid
            ];
            db("message_user")->insert($addmsg_userdata);
        }
        if($type == 5){
            $kminfo = db("km")->where("id",$shopid)->find();
            if ($kminfo["money"] == 0) {
                $money = "";
            } else {
                $money = "金币 = " . $kminfo["money"] . ",";
            }
            if ($kminfo["exp"] == 0) {
                $exp = "";
            } else {
                $exp = "经验 = " . $kminfo["exp"] . ",";
            }
            if ($kminfo["viptime"] == 0) {
                $vip = "";
            } else {
                $vip = "会员 = " . $kminfo["viptime"] . "天";
            }
            $content = "您于".date("Y-m-d H:i:s", time())."使用卡密成功，获得".$money.$exp.$vip;
            $addmessagedata = [
                "title" => "使用卡密成功",
                "content" => $content,
                "sender_id" => 0,
                "appid" => $this->app["appid"],
                "time" => date("Y-m-d H:i:s", time()),
                "type" => 5
            ];
            $msgid = db("message")->insertGetId($addmessagedata);
            //增加通知
            $addmsg_userdata = [
                "msg_id" => $msgid,
                "user_id" => $userid
            ];
            db("message_user")->insert($addmsg_userdata);
        }
    }
}
